<?php

namespace App\Jobs;

use App\Models\Common\Constant;
use App\Models\ParkingLot\ParkOrder;
use App\Models\Payment\PayCenter;
use App\Models\Payment\PaymentChannel;
use App\Models\Payment\PaymentOrder;
use App\Models\Payment\Platform\EbankPay;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;

class ClosePaymentOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $paymentOrder;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(PaymentOrder $paymentOrder)
    {
        $this->paymentOrder = $paymentOrder;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $paymentOrder = $this->paymentOrder;
        $paymentOrder->refresh();
        $order = null;

        $success = $paySuccess = false;
        try {
            \DB::beginTransaction();

            if (Constant::ORDER_STATUS_UNPAID === $paymentOrder->order_status) {

                $orderStatus = Constant::ORDER_STATUS_CLOSED;

                $paymentChannel = PaymentChannel::find($paymentOrder->payment_channel_id);
                switch (optional($paymentChannel)->category) {
                    case PaymentChannel::CATEGORY_EBANKPAY:
                        $response = (new EbankPay($paymentChannel))->toQuery($paymentOrder);
                        if ((\Arr::get($response, 'result_code') === 'SUCCESS') && (\Arr::get($response, 'return_code') === 'SUCCESS')) {
                            // 支付成功
                            if ('03' === Arr::get($response, 'uop_data.orderInfo.orderStatus')) {
                                $outTransactionID = Arr::get($response, 'uop_data.orderInfo.sysSeqNum');

                                $orderStatus = Constant::ORDER_STATUS_PAID;
                                $paymentOrder->paid_at = now()->toDateTimeString();
                                $paymentOrder->out_trade_no = $outTransactionID;
                                $paymentOrder->frozen_balance_amount = 0;
                                $paymentOrder->frozen_point = 0;
                                $paymentOrder->order_status = $orderStatus;

                                $paymentOrder->save();
                                $paySuccess = true;
                            }
                        }
                        break;
                    default:
                        break;
                }

                if (Constant::ORDER_STATUS_CLOSED === $orderStatus) {
                    $paymentOrder->order_status = Constant::ORDER_STATUS_CLOSED;
                    $paymentOrder->save();

                    if ($order = $paymentOrder->related) {

                        if (ParkOrder::class !== $paymentOrder->related_type) {
                            $order->order_status = Constant::ORDER_STATUS_CLOSED;
                            $order->save();
                        }
                    }

                    $success = true;
                }
            }

            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error('关闭支付单 失败', [
                'order_code' => $paymentOrder->order_code,
                'order_title' => $paymentOrder->order_title,
                'error' => $exception->getMessage(),
            ]);
        } finally {
            if ($success && $order) {
                if ($paymentChannel = PaymentChannel::find($order->payment_channel_id)) {
                    $payCenter = new PayCenter($paymentChannel);
                    $payResponse = $payCenter->toClose($order);
                }
            }
            if ($paySuccess) {
                //处理后续的各类系统订单逻辑
                PaymentOrderPaid::dispatch($paymentOrder)->onQueue(Constant::QUEUE_PAYMENT);
            }
        }
    }
}
